<template>
  <div class="destination-page">
    <page-banner title="探索目的地" subtitle="发现令人难忘的旅行胜地" />

    <!-- 优化筛选区域 -->
    <div class="filter-section">
      <div class="container">
        <!-- 高级筛选 -->
        <div class="filter-wrapper">
          <el-row :gutter="20">
            <el-col :md="6" :sm="12" :xs="24">
              <div class="filter-item">
                <span class="filter-label">区域</span>
                <el-select
                  v-model="selectedRegion"
                  placeholder="选择区域"
                  clearable
                  class="filter-select"
                >
                  <el-option
                    v-for="item in filterOptions.regions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    <span class="option-label">
                      <el-icon><Location /></el-icon>
                      {{ item.label }}
                    </span>
                    <span class="option-count">{{ item.count || 0 }}</span>
                  </el-option>
                </el-select>
              </div>
            </el-col>
            <el-col :md="6" :sm="12" :xs="24">
              <div class="filter-item">
                <span class="filter-label">季节</span>
                <el-select
                  v-model="selectedSeason"
                  placeholder="最佳季节"
                  clearable
                  class="filter-select"
                >
                  <el-option
                    v-for="item in filterOptions.seasons"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    <span class="option-label">
                      <el-icon><Calendar /></el-icon>
                      {{ item.label }}
                    </span>
                  </el-option>
                </el-select>
              </div>
            </el-col>
            <el-col :md="6" :sm="12" :xs="24">
              <div class="filter-item">
                <span class="filter-label">主题</span>
                <el-select
                  v-model="selectedTheme"
                  placeholder="选择主题"
                  clearable
                  class="filter-select"
                >
                  <el-option
                    v-for="item in filterOptions.themes"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    <span class="option-label">
                      <el-icon><Collection /></el-icon>
                      {{ item.label }}
                    </span>
                  </el-option>
                </el-select>
              </div>
            </el-col>
            <el-col :md="6" :sm="12" :xs="24">
              <div class="filter-item">
                <span class="filter-label">排序</span>
                <el-select
                  v-model="selectedSort"
                  placeholder="排序方式"
                  class="filter-select"
                >
                  <el-option
                    v-for="item in sortOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    <span class="option-label">
                      <el-icon><Sort /></el-icon>
                      {{ item.label }}
                    </span>
                  </el-option>
                </el-select>
              </div>
            </el-col>
          </el-row>

          <!-- 已选条件展示 -->
          <div class="selected-filters" v-if="hasSelectedFilters">
            <div class="selected-label">已选条件:</div>
            <div class="selected-tags">
              <el-tag
                v-if="selectedRegion"
                closable
                @close="selectedRegion = ''"
              >
                区域: {{ getFilterLabel("regions", selectedRegion) }}
              </el-tag>
              <el-tag
                v-if="selectedSeason"
                closable
                @close="selectedSeason = ''"
              >
                季节: {{ getFilterLabel("seasons", selectedSeason) }}
              </el-tag>
              <el-tag v-if="selectedTheme" closable @close="selectedTheme = ''">
                主题: {{ getFilterLabel("themes", selectedTheme) }}
              </el-tag>
            </div>
            <el-button
              type="primary"
              link
              @click="resetFilters"
              v-if="hasSelectedFilters"
            >
              清除全部
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 优化目的地列表 -->
    <div class="destinations-section">
      <div class="container">
        <!-- 添加加载状态 -->
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="3" animated />
          <el-skeleton :rows="3" animated />
          <el-skeleton :rows="3" animated />
        </div>
        
        <!-- 无数据提示 -->
        <el-empty v-else-if="destinations.length === 0" description="暂无目的地数据" />
        
        <el-row v-else :gutter="30">
          <el-col
            :xs="24"
            :sm="12"
            :md="8"
            v-for="item in destinations"
            :key="item.id"
          >
            <div class="destination-card" @click="viewDestination(item.id)">
              <div
                class="card-image"
                :style="{ backgroundImage: `url(${item.imageUrl})` }"
              >
                <div class="card-overlay">
                  <div class="card-tags">
                    <el-tag
                      size="small"
                      :style="getRegionTagStyle(item.region)"
                      >{{ item.region }}</el-tag
                    >
                    <el-tag size="small" :style="getTypeTagStyle(item.type)">{{
                      item.type
                    }}</el-tag>
                  </div>
                  <div class="card-stats">
                    <div class="stat-item">
                      <el-icon><View /></el-icon>
                      {{ formatNumber(item.visits) }}
                    </div>
                    <div class="stat-item">
                      <el-icon><Star /></el-icon>
                      {{ item.rating }}
                    </div>
                  </div>
                </div>
              </div>
              <div class="card-content">
                <h3>{{ item.name }}</h3>
                <p>{{ item.subtitle }}</p>
                <div class="card-features">
                  <el-tag
                    v-for="(feature, index) in item.features"
                    :key="index"
                    size="small"
                    :style="getFeatureTagStyle(index)"
                  >
                    {{ feature }}
                  </el-tag>
                </div>
                <div class="card-footer">
                  <div class="season-info">
                    <el-icon><Calendar /></el-icon>
                    <span>最佳季节: {{ item.bestSeason }}</span>
                  </div>
                  <el-button type="primary" size="small" round
                    >查看详情</el-button
                  >
                </div>
              </div>
            </div>
          </el-col>
        </el-row>

        <!-- 分页器 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-if="total > 0"
            background
            layout="prev, pager, next"
            :total="total"
            :current-page="currentPage"
            :page-size="9"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
// 导入相关API
import { ref, computed, watch, onMounted } from "vue";
import { useRouter } from "vue-router";
 import PageBanner from "@/components/PageBanner.vue";
import { formatNumber } from "@/utils/format";
import {
  Location,
  Calendar,
  Collection,
  View,
  Star,
  Sort,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { 
  pageDestinations, 
  getDestinationFilterOptions 
} from "@/api/destination";

const router = useRouter();

// 状态变量声明
const loading = ref(false);
const total = ref(0);
const currentPage = ref(1);
const destinations = ref([]);
const selectedRegion = ref("");
const selectedType = ref("");
const selectedSeason = ref("");
const selectedTheme = ref("");
const selectedSort = ref("visits"); // 默认按访问量排序

// 查询参数
const queryParams = ref({
  keyword: "",
  region: "",
  type: "",
  season: "",
  theme: "",
  orderBy: "visits"
});

// 筛选选项配置
const filterOptions = ref({
  types: [],
  regions: [],
  seasons: [],
  themes: []
});

// 排序选项
const sortOptions = [
  { label: "默认排序", value: "visits" },
  { label: "人气最高", value: "visits" },
  { label: "评分最高", value: "rating" },
  { label: "最新上线", value: "createTime" },
];

// 获取目的地列表
const fetchDestinations = async () => {
  loading.value = true;
  try {
    // 更新查询参数
    queryParams.value = {
      keyword: "",
      region: selectedRegion.value || undefined,
      type: selectedType.value || undefined,
      season: selectedSeason.value || undefined,
      theme: selectedTheme.value || undefined,
      orderBy: selectedSort.value
    };

    const result = await pageDestinations(currentPage.value, 9, queryParams.value);
    
    if (result) {
      destinations.value = result.records || [];
      total.value = result.total || 0;
      
      // 处理图片URL
      destinations.value = destinations.value.map(dest => ({
        ...dest,
        imageUrl: dest.coverImages && dest.coverImages.length > 0 
          ? dest.coverImages[0] 
          : (dest.imageUrl || 'https://via.placeholder.com/400x300?text=暂无图片'),
        features: dest.features || dest.tags || [],
        bestSeason: dest.bestSeason || dest.bestTimeToVisit || '四季皆宜'
      }));
    }
  } catch (error) {
    console.error("获取目的地列表失败:", error);
    ElMessage.error("获取数据失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 获取筛选选项
const fetchFilterOptions = async () => {
  try {
    const options = await getDestinationFilterOptions();
    console.log('API返回的筛选选项:', options);

    
    // 更新筛选选项
    if (options) {
      if (options.regions) {
        filterOptions.value.regions = options.regions.map(item => ({
          label: item.name,
          value: item.value,
          count: item.count
        }));
      }
      
      if (options.types) {
        filterOptions.value.types = options.types.map(item => ({
          label: item.name,
          value: item.value
        }));
      }
      
      if (options.seasons) {
        filterOptions.value.seasons = options.seasons.map(item => ({
          label: item.name,
          value: item.value
        }));
      }
      
      if (options.themes) {
        filterOptions.value.themes = options.themes.map(item => ({
          label: item.name,
          value: item.value
        }));
      }
    }
  } catch (error) {
    console.error("获取筛选选项失败:", error);
    // 使用默认选项
    filterOptions.value = {
      types: [
        { label: "自然风光", value: "nature" },
        { label: "人文古迹", value: "culture" },
        { label: "民族风情", value: "ethnic" },
        { label: "美食之旅", value: "food" },
      ],
      regions: [
        { label: "北部", value: "north", count: 12 },
        { label: "南部", value: "south", count: 15 },
        { label: "东部", value: "east", count: 8 },
        { label: "西部", value: "west", count: 18 },
      ],
      seasons: [
        { label: "春季", value: "spring" },
        { label: "夏季", value: "summer" },
        { label: "秋季", value: "autumn" },
        { label: "冬季", value: "winter" },
      ],
      themes: [
        { label: "摄影创作", value: "photo" },
        { label: "户外探险", value: "outdoor" },
        { label: "文化体验", value: "culture" },
        { label: "休闲度假", value: "leisure" },
      ],
    };
  }
};

// 监听筛选条件变化
watch([selectedRegion, selectedType, selectedSeason, selectedTheme, selectedSort], () => {
  currentPage.value = 1; // 重置页码
  fetchDestinations();
});

// 页码改变
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchDestinations();
  // 添加平滑滚动到顶部
  window.scrollTo({
    top: 0,
    behavior: "smooth",
  });
};

onMounted(() => {
  fetchFilterOptions();
  fetchDestinations();
});

const getRegionTagStyle = (region) => ({
  backgroundColor:
    {
      北部: "#e8f4ff",
      南部: "#fff2e8",
      东部: "#f6ffed",
      西部: "#fff7e6",
    }[region] || "#f5f5f5",
  color: "#666666",
  border: "none",
});

const getTypeTagStyle = (type) => ({
  backgroundColor:
    {
      自然风光: "#e6fffb",
      人文古迹: "#fff0f6",
      民族风情: "#f9f0ff",
    }[type] || "#f5f5f5",
  color: "#666666",
  border: "none",
});

const getFeatureTagStyle = (index) => ({
  backgroundColor: ["#e6fffb", "#fff0f6", "#f0f5ff", "#f6ffed"][index % 4],
  color: "#666666",
  border: "none",
});

// 添加目的地查看方法
const viewDestination = (id) => {
  router.push(`/destination/${id}`);
};

// 判断是否有已选条件
const hasSelectedFilters = computed(() => {
  return selectedRegion.value || selectedSeason.value || selectedTheme.value;
});

// 获取筛选项标签文本
const getFilterLabel = (type, value) => {
  const option = filterOptions.value[type].find((item) => item.value === value);
  return option ? option.label : "";
};

// 重置筛选条件
const resetFilters = () => {
  selectedRegion.value = "";
  selectedSeason.value = "";
  selectedTheme.value = "";
  selectedSort.value = "visits"; // 修改为默认值visits
  currentPage.value = 1;
  fetchDestinations(); // 添加重新获取数据
};
</script>

<style scoped>
.destination-banner {
  height: 280px; /* 修改为与私人定制页面一致 */
  margin-top: var(--header-height); /* 改用 margin-top 而不是 padding-top */
  background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)),
    linear-gradient(45deg, var(--primary-color), #36cfc9);
  background-size: cover;
  background-position: center;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  color: white;
}

.banner-content h1 {
  font-size: 2.5rem;
  margin-bottom: 1rem;
}

/* 优化筛选区域样式 */
.filter-section {
  background: white;
  padding: 20px 0;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: var(--header-height);
  z-index: 10;
}

.filter-wrapper {
  padding: 0;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-label {
  min-width: 45px;
  color: var(--text-color);
  font-size: 0.95rem;
  font-weight: 500;
}

.filter-select {
  flex: 1;
}

.option-label {
  display: flex;
  align-items: center;
  gap: 8px;
}

.option-count {
  color: var(--text-color-secondary);
  font-size: 0.9rem;
}

.selected-filters {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px dashed var(--border-color);
}

.selected-label {
  color: var(--text-color-secondary);
  font-size: 0.95rem;
}

.selected-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  flex: 1;
}

.destinations-section {
  padding: 40px 0;
  background: var(--light-bg);
}

.destination-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 30px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.destination-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.card-image {
  height: 240px;
  background-size: cover;
  background-position: center;
  position: relative;
}

.card-overlay {
  position: absolute;
  inset: 0;
  background: linear-gradient(
    to bottom,
    rgba(0, 0, 0, 0.2),
    rgba(0, 0, 0, 0.6)
  );
  padding: 20px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.destination-card:hover .card-overlay {
  opacity: 1;
}

.card-tags {
  display: flex;
  gap: 8px;
}

.card-stats {
  display: flex;
  gap: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: white;
  font-size: 0.9rem;
}

.card-content {
  padding: 20px;
}

.card-content h3 {
  margin: 0 0 8px;
  font-size: 1.3rem;
  color: var(--text-color);
}

.card-content p {
  margin: 0 0 15px;
  color: var(--text-color-secondary);
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.card-features {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 15px;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
  border-top: 1px dashed var(--border-color);
}

.season-info {
  display: flex;
  align-items: center;
  gap: 6px;
  color: var(--text-color-secondary);
  font-size: 0.9rem;
}

.pagination-wrapper {
  margin-top: 40px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .filter-section {
    padding: 20px 0;
    position: static;
  }

  .filter-item {
    margin-bottom: 15px;
  }

  .selected-filters {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .selected-tags {
    margin-bottom: 10px;
  }

  .card-image {
    height: 200px;
  }

  .card-content h3 {
    font-size: 1.1rem;
  }
}
.loading-container {
  padding: 20px;
}

.el-empty {
  padding: 40px 0;
}
</style>
